import 'package:flutter/material.dart';
import 'package:flutter_simple_treeview/flutter_simple_treeview.dart';
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/controller/cache.dart';
import 'package:ichinesereader/controller/evaluation.dart';
import 'package:ichinesereader/models/evaluation/evaluationSkillType.dart';
import 'package:ichinesereader/models/evaluation/skillPointsResult.dart';
import 'package:ichinesereader/pages/common/circularImage.dart';
import 'package:syncfusion_flutter_gauges/gauges.dart';
import 'package:get/get.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:hive_flutter/hive_flutter.dart';
import '../../themes/appTheme.dart';

class EvaluationLinguisticSkillsTreeView extends StatefulWidget {
  EvaluationLinguisticSkillsTreeView({Key? key}) : super(key: key);

  @override
  EvaluationLinguisticSkillsTreeViewState createState() =>
      EvaluationLinguisticSkillsTreeViewState();
}

class EvaluationLinguisticSkillsTreeViewState
    extends State<EvaluationLinguisticSkillsTreeView> {
  final EvaluationController _evaluationController = Get.find();
  final box = Hive.box('appconfig');

  //var graph = GF.Graph()..isTree = true;
  late List<SkillPointsDataTree> _evaluationSkillsDataTree;
  final TreeController _treeController = TreeController(allNodesExpanded: true);
  String _skillType = Constants.evaluationSkillTypes[0].skill.toString();
  String _classId = '';
  bool isTeacher = false;

  @override
  void initState() {
    isTeacher = box.get(CacheManagerKey['nanhairole'].toString()) ==
        Constants.NanhaiRole_Teacher;
    if (isTeacher) {
      _classId = box.get(CacheManagerKey['currentclass'].toString());
    } else {
      _classId = '';
    }

    Future.delayed(Duration(milliseconds: 200), () {
      _evaluationController.fetchEvaluationSkillPointsData(
          _classId, _evaluationController.currentLevel.value.toString());
    });

    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  void setSkillType(String type) {
    setState(() {
      _skillType = type;
    });
  }

  List<TreeNode> generateTree(SkillPointsDataTree root) {
    var nodes = <TreeNode>[];
    nodes.add(toTreeNodes(root));
    return nodes;
  }

  TreeNode toTreeNodes(SkillPointsDataTree node) {
    var result = new TreeNode();
    if (node.skills != null) {
      result = TreeNode(
          key: ValueKey(node.id),
          content: rectangleWidget(node),
          children: node.skills!.map((element) {
            return toTreeNodes(element);
          }).toList());
    }
    return result;
  }

  Widget buildTree(String type) {
    try {
      SkillPointsDataTree rootTree = this
          ._evaluationSkillsDataTree
          .where((tree) => tree.name == type)
          .first;
      return TreeView(
        nodes: generateTree(rootTree),
        treeController: _treeController,
      );
    } on FormatException catch (e) {
      return Text(e.message);
    }
  }

  buildFloatingActionButtons() {
    List<EvaluationSkillType> skillTypes =
        Constants.evaluationSkillTypes.take(2).toList();

    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: skillTypes
          .map((state) => Padding(
                padding: const EdgeInsets.only(bottom: 8.0),
                child: SizedBox(
                  width: 45.0,
                  height: 45.0,
                  child: FloatingActionButton(
                      heroTag: state.skill.toString(),
                      tooltip: state.skill!.tr,
                      onPressed: () {
                        setSkillType(state.skill.toString());
                      },
                      elevation: 5,
                      splashColor: Colors.grey,
                      child: Image.asset(
                        state.image.toString(),
                        width: 50,
                        height: 50,
                      )),
                ),
              ))
          .toList(),
    );
  }

  @override
  Widget build(BuildContext context) {
    Log.debug(
        'Build evaluation linguistic skills treeview teacher/student graph');
    box.put('SkillType', 'LanguageSkill');
    ///////////Language Skills页面//////////////////
    return Scaffold(
        backgroundColor: Colors.transparent,
        floatingActionButton: buildFloatingActionButtons(),
        // FloatingActionButtonsEvaluationSkills(isProficiency: false),
        floatingActionButtonLocation: FloatingActionButtonLocation.miniEndTop,
        body: Column(
          mainAxisSize: MainAxisSize.max,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Expanded(
                ///////树状图的背景//////
                child: Container(
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(3.0),
                color: Get.isDarkMode
                    ? AppTheme.colors.darkTheme2
                    : Colors.white.withOpacity(0.3),
              ),
              padding: EdgeInsets.only(
                top: 30.0,
                left: 12.0,
              ),
              child: SingleChildScrollView(
                child: _evaluationController.obx(
                  (data) {
                    _evaluationSkillsDataTree =
                        _evaluationController.evaluationSkillPointsDataTree;
                    if (_evaluationSkillsDataTree.isNotEmpty) {
                      return buildTree(_skillType);
                    } else {
                      return Text('');
                    }
                  },
                  onEmpty: Center(child: Text('Data not available ...'.tr)),
                  onLoading: Container(),
                ),
              ),
            ))
          ],
        ));
  }

  Widget rectangleWidget(dynamic node) {
    SkillPointsDataTree tree = node as SkillPointsDataTree;
    double _accuracy = 0;

    if (tree.skills != null && tree.skills!.isNotEmpty) {
      double _totalAccuracy = 0;
      tree.skills?.forEach((skill) {
        _accuracy = skill.correct != 0 && skill.total != 0
            ? (skill.correct! / skill.total!) * 100
            : 0;
        _totalAccuracy = _totalAccuracy + _accuracy;
      });
      _accuracy = _totalAccuracy / tree.skills!.length;
    } else {
      _accuracy = tree.correct != 0 && tree.total != 0
          ? (tree.correct! / tree.total!) * 100
          : 0;
    }

    String image =
        'https://resources.ichinesereader.com/media/evaluation/bubble_yellow_${_accuracy.toInt()}.gif';

    return InkWell(
      /////////////////////单个技能选项方块////////
      child: Container(
          margin: EdgeInsets.all(6.0),
          padding: EdgeInsets.all(9.0),
          decoration: BoxDecoration(
            color: Get.isDarkMode
                ? Colors.black.withOpacity(0.6)
                : Colors.white.withOpacity(0.6),
            borderRadius: BorderRadius.circular(12.0),
            boxShadow: [
              BoxShadow(
                blurRadius: 9.0,
                spreadRadius: 1.0,
                color: Get.isDarkMode
                    ? Colors.transparent
                    : Get.theme.primaryColor.withOpacity(0.8),
                offset: Offset(6.0, 6.0),
              ),
            ],
          ),
          child: Row(
            children: [
              Container(
                width: 60,
                height: 60,
                child: SfRadialGauge(
                  axes: [
                    RadialAxis(
                        minimum: 0,
                        maximum: 100,
                        startAngle: 0,
                        endAngle: 360,
                        interval: 1,
                        showTicks: false,
                        showLabels: false,
                        axisLineStyle: AxisLineStyle(thickness: 6),
                        pointers: <GaugePointer>[
                          RangePointer(
                              value: _accuracy,
                              width: 6,
                              color: Colors.tealAccent[200],
                              cornerStyle: CornerStyle.bothCurve)
                        ],
                        showFirstLabel: false,
                        annotations: <GaugeAnnotation>[
                          GaugeAnnotation(
                              widget: NonCacheCircularImage(image, 60),
                              angle: 90,
                              positionFactor: 0)
                        ])
                  ],
                ),
              ),
              SizedBox(
                width: 9.0,
              ),
              //////////格式文字部分//////////////
              RichText(
                text: TextSpan(
                  children: [
                    TextSpan(
                        text: '${tree.name.toString()}\n',
                        style: TextStyle(
                            color: Get.isDarkMode
                                ? Get.theme.primaryColorDark
                                : Colors.black,
                            fontFamily: 'Montserrat',
                            fontSize: 15.0)),
                    TextSpan(
                        text: 'Correct:  ',
                        style:
                            TextStyle(fontSize: 12.0, color: Colors.blueGrey)),
                    TextSpan(
                        text: '${tree.correct.toString()}     ',
                        style: TextStyle(
                            color: Get.theme.primaryColorDark,
                            fontSize: 18.0,
                            fontWeight: FontWeight.bold)),
                    TextSpan(
                        text: 'Total:  ',
                        style:
                            TextStyle(fontSize: 12.0, color: Colors.blueGrey)),
                    TextSpan(
                        text: '${tree.total.toString()}',
                        style: TextStyle(
                            color: Get.theme.primaryColorDark,
                            fontSize: 18.0,
                            fontWeight: FontWeight.bold)),
                  ],
                ),
              ),
            ],
          )),
    );
  }
}
